import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/app/prisma/client';
import getUserId from '@/utils/getUserId';

export async function GET(req: NextRequest, { params }: { params: { conversationId: string } }) {
  try {
    const userId = getUserId(req);
    if (!userId) {
      return NextResponse.json({ error: '请先登录' }, { status: 401 });
    }

    const { conversationId } = params;

    // 1. 验证用户是否是会话的参与者
    const participation = await prisma.conversationParticipant.findUnique({
      where: {
        userId_conversationId: {
          userId: userId,
          conversationId: conversationId,
        },
      },
    });

    if (!participation) {
      return NextResponse.json({ error: '你无权访问此会话' }, { status: 403 });
    }

    // 2. 获取会话，并包含关联的群组信息及成员
    const conversation = await prisma.conversation.findUnique({
      where: { id: conversationId },
      include: {
        group: {
          include: {
            owner: {
              select: { id: true, username: true, avatar: true },
            },
            members: {
              include: {
                user: {
                  select: { id: true, username: true, avatar: true },
                },
              },
              orderBy: {
                joinedAt: 'asc',
              },
            },
          },
        },
      },
    });
    
    if (!conversation || !conversation.group) {
        return NextResponse.json({ error: '找不到对应的群聊信息' }, { status: 404 });
    }
    
    const { group } = conversation;
    const formattedMembers = group.members.map(m => ({
        ...m.user,
        role: m.role,
        joinedAt: m.joinedAt,
    }));


    const response = {
        id: group.id,
        name: group.name,
        avatar: group.avatar,
        ownerId: group.ownerId,
        members: formattedMembers,
    }

    return NextResponse.json(response);
  } catch (error) {
    console.error('获取群聊详情失败:', error);
    return NextResponse.json({ error: '服务器错误' }, { status: 500 });
  }
} 